$(function() {
	if (document.getElementById("table_box_common")) {

		if (User.id == 0 || User.id == '') {
			return false;
		}
		// 普通编辑、高级编辑的切换事件
		WendaAsk.selectedTab();

		// 文本框的事件
		WendaAsk.askTxtEvent();

		// 按钮事件
		WendaAsk.askBtnEvent();

		// 离开页面提醒
		WendaAsk.leavePageAlertEvent();
		// 输入标签标题提示
		WendaAsk.tagTips();
		// 输入问题标题提示
		if (!WendaAsk.isShare) {
			WendaAsk.titleTips();
		}
		// 屏蔽默认事件
		$("#my_question_form").find("textarea[id='title']").bind("keydown",
				function(e) {
					if (e.keyCode == 13) {
						return false;
					}
				});
		
		
		// 分享
		if (WendaAsk.isShare) {
			// $("#my_question_form >ul >li").each(function(){
			// var $this = $(this);
			// if($this.attr("id")=='li_common'){
			// $this.children().text("快速分享");
			// }
			// });

			$("#li_common").text("快速分享");

			$("#table_box_btns").find("input[type='button']").val("确认分享");
			var p = $("#table_box_advanced").children("p")[0];
			var html = $(p).html();
			html = html.replace("问题", "分享");
			$(p).html(html);
		}
	}

});

// 问答中的提问
var WendaAsk = {
	isSubmit : false,
	searchQTitleObj : null,
	addQTagsListObj : null,
	winUrl : window.location.href,
	isShare : Constans.IS_SHARE,
	Constants : {
		COMMON : "common",
		ADVANCED : "advanced",
		WRITE_ASK : Constans.IS_SHARE ? Constants.WRITE_SHARE
				: Constants.WRITE_ASK,
		WRITE_ASK_DETAIL : Constans.IS_SHARE ? Constants.WRITE_SHARE_DETAIL
				: Constants.WRITE_ASK_DETAIL
	},
	editType : "common",
	timing : function(fun) {// 定时，一秒后恢复按钮可点击
		var timeout = setTimeout(function() {
			// 一秒后才执行该代码
			if (typeof (fun) == "function")
				fun();
			if (typeof (fun) == "string") {
				try {
					eval(fun);
				} catch (e) {
				}
			}

			window.clearTimeout(timeout);
		}, 1000);
	},
	// 却换事件
	selectedTab : function() {
		$("#table_box_btns >a").bind("click", function() {
			var $this = $(this);
			WendaAsk.changedTab($this);
		});
	},
	// 更切换
	changedTab : function($this) {
		// $this.siblings().removeClass("selected");
		// $this.addClass("selected");
		if ($this.attr("id") == 'li_common') {
			WendaAsk.editType = WendaAsk.Constants.COMMON;

			// $("#table_box_common").show();
			$("#table_box_advanced").hide("fast", function() {
				$this.siblings("a").show();
				$this.hide();
			});

			WendaAsk.searchQTitleObj = WendaAsk.QTitleObjCommon;
		} else if ($this.attr("id") == 'li_advanced') {

			WendaAsk.editType = WendaAsk.Constants.ADVANCED;
			// $("#table_box_common").hide();
			$("#table_box_advanced").show("fast", function() {
				$this.siblings("a").show();
				$this.hide();
			});

			// WendaAsk.searchQTitleObj = WendaAsk.QTitleObjAdvanced;
		}

		var val = $("#table_box_common").find("textarea[id='title']").val();
		if (val != WendaAsk.Constants.WRITE_ASK) {
			$("#table_box_common").find("textarea[id='title']").val(val);
		}
		WendaAsk.searchQTitleObj = WendaAsk.QTitleObjCommon;
	},
	//取一段内容的所占字节数
	checkStrlength:function(chars) {
	    var sum = 0;
	    for ( var i = 0; i < chars.length; i++) {
	        var c = chars.charCodeAt(i);
	        if ((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f)) {
	            sum++;
	        } else {
	            sum += 2;
	        }
	    }
	    return sum;
	},
	getLenIndex:function(chars,length) {
	    var sum = 0;
	    for ( var i = 0; i < chars.length; i++) {
	        var c = chars.charCodeAt(i);
	        if ((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f)) {
	            sum++;
	        } else {
	            sum += 2;
	        }
	        
	        if(sum > length){
	        	return i;
	        }
	    }
	    return 0;
	},
	// 问题输入框事件
	askTxtEvent : function() {
		var _this = this;
		var __questionArea = $("#my_question_form").find("textarea[id='title']");
		$("#my_question_form").find("textarea[id='title']").val(
				WendaAsk.Constants.WRITE_ASK);
		__questionArea.bind("focus",function() {
			if ($.trim($(this).val()) == WendaAsk.Constants.WRITE_ASK) {
				$(this).val("");
				$("#table_box_btns").show();
				var $this = $("#li_advanced");
				WendaAsk.changedTab($this);
				
			}
		});

		__questionArea.bind("focusout",function(e) {
			if ($.trim($(this).val()) == '') {
				$(this).val(WendaAsk.Constants.WRITE_ASK);
			}
			setTimeout(function(){
				WendaAsk.searchQTitleObj.hide();
			},200)
		});
		
		//让提问输入框只能输入72个字母，36个汉字
		__questionArea.keyup(function(event){
			if(_this.checkStrlength($(this).val()) > 72){
				var _v = $(this).val();
				var _index = _this.getLenIndex(_v,72);
				var _subStr = _v.charAt(_index);
				$(this).val(_v.substring(0,_index));
			}
		});
		setTimeout(function() {
			var iframe = $("#table_box_advanced").find("iframe")[0];
			var iframeWin = iframe.contentWindow;
			var iframeBody = iframe.contentWindow.document.body;
			addQDetail.html(WendaAsk.Constants.WRITE_ASK_DETAIL);
			$(iframeWin).bind("focus", function() {
				var html = addQDetail.html();

				if ($(html).children().length == 1) {
					html = $(html).html();
					html = $(html).text();
				}

				var detailTips = $(WendaAsk.Constants.WRITE_ASK_DETAIL).text();

				if ($.trim(html) == $.trim(detailTips)) {
					addQDetail.html("");
				}
			});

			$("#q_description").find("div[class='ke-toolbar']").bind("click",
					function() {
						setTimeout(function() {
							iframeWin.focus();
						}, 100);
					});

			$("body").bind("mousedown", function(e) {
				if ($.trim(addQDetail.text()).length == 0) {
					addQDetail.html(WendaAsk.Constants.WRITE_ASK_DETAIL);
				}
			});
		}, 100);
	},
	// 按钮事件
	askBtnEvent : function() {
		$("#table_box_btns")
				.find("a[data-name='cancel']")
				.bind(
						"click",
						function() {
							$("#my_question_form").find("textarea[id='title']")
									.val(WendaAsk.Constants.WRITE_ASK);
							if (WendaAsk.editType == WendaAsk.Constants.COMMON) {
								// $("#my_question_form").find("textarea[id='title']").val(WendaAsk.Constants.WRITE_ASK);
							} else if (WendaAsk.editType == WendaAsk.Constants.ADVANCED) {
								addQDetail
										.html(WendaAsk.Constants.WRITE_ASK_DETAIL);

								var $this = $("#li_common");
								WendaAsk.changedTab($this);
							}

							// $("#table_box_btns").hide();
						});

		WendaAsk.saveBtnEvent();
	},
	// 保存按钮
	saveBtnEvent : function() {
		$("#table_box_btns").find("input[data-name='save']").bind(
				"click",
				function() {
					$(this).unbind("click");
					WendaAsk.timing(function() {
						WendaAsk.saveBtnEvent();
					});
					var title = $("#my_question_form").find(
							"textarea[id='title']").val();
					WendaAsk.askQ();
				});
	},
	// 提问
	askQ : function() {
		var ctype = 0;
		var req_url = "json/questionJsonAction!askQuestion.action";
		if (WendaAsk.isShare) {
			req_url = "json/questionJsonAction!addShare.action";
			ctype = 1;
		} else {
			ctype = 0;
		}

		if (WendaAsk.editType == WendaAsk.Constants.COMMON) {
			WendaAsk.askCommon('', ctype, req_url);
		} else if (WendaAsk.editType == WendaAsk.Constants.ADVANCED) {
			WendaAsk.askAdvanced('', ctype, req_url);
		}
	},
	// 普通提问
	askCommon : function(ptag, ctype, req_url) {
		var qtitle = $("#table_box_common").find("textarea").val();

		if (WendaAsk.Constants.WRITE_ASK == qtitle) {
			if (ctype == 0)
				Wenda.alert("请输入你的问题");
			else
				Wenda.alert("请输入你的分享");
			return;
		}

		if (DZQCheckForUser() || WendaAsk.isSubmit)
			return;
		if (!checkAuth(DZQ_ACTIONS.ASK_QUESTION)) {
			return;
		}

		this.saveAsk(req_url, qtitle, '', '', ctype, '', '');
	},
	// 高级提问
	askAdvanced : function(ptag, ctype, req_url) {
		if (DZQCheckForUser() || WendaAsk.isSubmit)
			return;
		if (!checkAuth(DZQ_ACTIONS.ASK_QUESTION)) {
			return;
		}

		// 获取问题
		// var qtitle =
		// $("#table_box_advanced").find("textarea[id='title']").val();
		var qtitle = $("#table_box_common").find("textarea").val();
		if (WendaAsk.Constants.WRITE_ASK == qtitle) {
			if (ctype == 0)
				Wenda.alert("请输入你的问题");
			else
				Wenda.alert("请输入你的分享");
			return;
		}

		// var qcontent = $("#wtbc").val();
		// 获取问题补充
		var qcontent = addQDetail.html();
		if ($(WendaAsk.Constants.WRITE_ASK_DETAIL).html() == $(
				$(qcontent).html().replace(/(\n|\t)/g,"")).html()) {
			qcontent = "";
		}
		

		// 获取标签
		var huati = $("#addQ_tags").val() + " ";

		if (ptag == null || $.trim(ptag).length == 0) {
			var ta = $("#addQ_tagList").find("span");
			for ( var i = 0; i < ta.length; i++) {
				huati += $(ta[i]).children().first().text() + " ";
			}
		} else {
			huati = ptag;
		}

		this.saveAsk(req_url, qtitle, qcontent, huati, ctype, '', '');
	},
	// 保存提问
	saveAsk : function(req_url, qtitle, qcontent, huati, ctype, isnm, domainId,
			reloadUrl) {
		if (WendaAsk.isSubmit)
			return;
		WendaAsk.isSubmit = true;
		// 删除内容前面无用的标签
		qcontent = Wenda.removeConBefHtmlTags(qcontent, "BR");
		;
		var specialtag = $("#specialtag");// 专题专用
		var tag;
		if (specialtag.length == 0) {
			tag = huati;
		} else {
			tag = huati + " " + specialtag.val();
		}
		Wenda.post(Constans.BASE_PATH + req_url, {
			"question.title" : qtitle,
			"question.content" : qcontent,
			"question.tag" : tag,
			"isAnonymous" : isnm,
			"domainId" : domainId,
			"ctype" : ctype
		}, function(data) {
			WendaAsk.isSubmit = false;
			if (data.isLogin == 'no') {
				//
				window.onbeforeunload = null;
				window.location.href = Constans.BASE_PATH + "login.jsp";
				return;
			}
			if (data.messages != '') {
				Wenda.alert(data.messages);
				return;
			}
			var questionId = data.question.id;
			if (questionId > 0 && !reloadUrl) {// 问题添加成功
				//
				window.onbeforeunload = null;
				if (WendaAsk.isShare) {
					window.location.href = Constans.BASE_PATH
							+ "question/question!fetchShareInfo.action?qid="
							+ questionId;
				} else {
					if (specialtag.length == 0) {
						window.location.href = Constans.BASE_PATH
								+ "question/question!fetchQuestion.action?qid="
								+ questionId;
					} else {
						alert("提问成功！");
						window.location.href = window.location.href;
					}

				}

			} else {// 活动分享
				Wenda.closeWin();

				try {
					window.location.reload();
				} catch (e) {
					window.location.href = reloadUrl;
				}
				Wenda.alert("圈内分享成功");
			}
		}, 'json');

	},
	// 离开页面时提示事件
	leavePageAlertEvent : function() {
		if (!document.getElementById("table_box_common")) {
			return;
		}

		window.noUseLink();
		/*
		 * if($.browser.msie){ window.setTimeout(function(){
		 * $("a").each(function(){ var href = this.href; if(!href || (0 >
		 * href.indexOf("wenda/") && 0 > href.indexOf("http://") && 0 >
		 * href.indexOf("https://"))){ //this.href = "###";
		 * $(this).bind("click",function(e){ return false; }); } }); },500); }
		 */
		window.onbeforeunload = function(event) {
			var conType = "提问";
			if (WendaAsk.isShare) {
				conType = "分享";
			}

			var msg = "你的" + conType + "尚未提交，离开本页将会丢失，确定要离开吗？";
			// if(event.clientX>document.body.clientWidth&&event.clientY<0||event.altKey)
			// {
			// return "654564";
			// }
			if (WendaAsk.editType == WendaAsk.Constants.COMMON) {
				var val = $("#table_box_common").find("textarea[id='title']")
						.val();
				if (val == WendaAsk.Constants.WRITE_ASK) {
					msg = null;
				}
			} else if (WendaAsk.editType == WendaAsk.Constants.ADVANCED) {
				var val = $("#table_box_common").find("textarea[id='title']")
						.val();
				if (val == WendaAsk.Constants.WRITE_ASK) {
					msg = null;
				}
			}

			if (msg != null) {
				if (/Firefox[\/\s](\d+)/.test(navigator.userAgent)
						&& new Number(RegExp.$1) >= 4) {
					if (confirm(msg)) {
						history.go();
					} else {
						window.setTimeout(function() {
							window.stop();
						}, 1);
					}
				} else {
					return "你的" + conType + "尚未提交，离开本页将会丢失";
				}
			}

		};

	},
	// tag提示
	tagTips : function() {
		WendaAsk.addQTagsListObj = $("#addQ_tags").wendaDropDrownList({
			"width" : 395,
			"topparent" : "true",
			"searchFun" : "WendaAsk.sendSearchTags",
			"enterFun" : "WendaAsk.addTagsHtml"
		});

		scrollEvent = "WendaAsk.addQTagsListObj.setConfig({width:395})";
		setTimeout(function() {
			$("#addQ_tags").bind(
					"focus",
					function() {
						var val = $("#table_box_advanced").find(
								"textarea[id='title']").val();
						if (val != WendaAsk.Constants.WRITE_ASK)
							WendaAsk.sendSearchTagsByQ(val);
					});
		});
	},
	/**
	 * 发送搜索tag请求
	 * 
	 * @param keyword
	 */
	sendSearchTagsByQ : function(keyword) {
		Wenda.post(Constans.BASE_PATH
				+ "json/searchJsonAction!sugTagByQuestion.action", {
			"keyword" : keyword
		}, function(datas) {
			WendaAsk.searchTagListCallBack(datas, keyword, "tag");
		}, 'json');
	},
	/**
	 * 发送搜索tag请求
	 * 
	 * @param keyword
	 */
	sendSearchTags : function(keyword) {
		Wenda.post(basePath + "json/searchJsonAction!searchTags.action", {
			"keyword" : keyword
		}, function(datas) {
			WendaAsk.searchTagListCallBack(datas, keyword, "tag");
		}, 'json');
	},
	/**
	 * 搜索回调
	 * 
	 * @param datas
	 * @param keyword
	 * @param type
	 */
	searchTagListCallBack : function(datas, keyword, type) {
		var html = "";

		var fun = 'WendaAsk.addTagsHtml';
		if (datas.tagSuggestionItems != null) {
			for ( var i = 0; i < datas.tagSuggestionItems.length; i++) {
				html += WendaAsk
						.parseTagsData(datas.tagSuggestionItems[i], fun);
			}
		}

		WendaAsk.addQTagsListObj.setHtml({
			"html" : html,
			"keyword" : keyword
		});

	},
	/**
	 * 拼装html
	 * 
	 * @param tag
	 * @returns {String}
	 */
	parseTagsData : function(tag, fun) {
		if (tag == null)
			return "";
		var html = "";
		html += '<div style="-moz-user-select: none;cursor:pointer">'
				+ '<img src="' + Constans.IMG_BASE_URL + "m_" + tag.img
				+ '" style="-moz-user-select: none;width:25px;height:25px" >'
				+ '&nbsp;&nbsp;<a href="#" style="-moz-user-select: none;">'
				+ (tag.name || "") + '</a>'
				+ '<span style="-moz-user-select: none;"><!--又称'
				+ '<b style="-moz-user-select: none;">g</b>ay，-->&nbsp;&nbsp;'
				+ tag.fc + '个热门问答 ' + '</span>' + '</div>';

		return html;
	},

	addTagsHtml : function(text) {
		if (!text) {
			if (cacheData["listIndex"] == -1)
				cacheData["listIndex"] = 0;
			text = $("#searchList").children().eq(cacheData["listIndex"]).find(
					"a").text();
		}

		if (text != null && text.length > 0
				&& $("#addQ_tagList").html().indexOf("rmid-" + text) < 0) {
			var tagHtml = '<span class="mods">'
					+ '<a href="'
					+ Constans.BASE_PATH
					+ 'tag/tagAction!tagindex.action?tagName='
					+ text
					+ '">'
					+ text
					+ '</a>'
					+ '<a name="remove" href="#" onclick="javascript:$(this).parent().remove();" id="rmid-'
					+ text + '"><img class="del" src="' + Constans.IMG_BASE_URL
					+ 'authentication.gif"/></a></span>';

			var $tagList = $("#addQ_tagList");
			$tagList.append(tagHtml);
			// $("#addQ_tags").val("");
		}
	},
	// 标题提示
	titleTips : function() {
		var $common = $("#table_box_common").find("textarea[id='title']");
		WendaAsk.QTitleObjCommon = $common.wendaDropDrownList({
			"width" : 395,
			"top" : $common.offset().top + $common.height(),
			"left" : $common.offset().left,
			"searchFun" : "WendaAsk.sendSearchQuestion"
		// "enterFun":"enterAction"
		});

		// var $advanced =
		// $("#table_box_advanced").find("textarea[id='title']");
		// WendaAsk.QTitleObjAdvanced = $advanced.wendaDropDrownList({
		// "width":395,
		// "top":$advanced.offset().top+$advanced.height(),
		// "left":$advanced.offset().left,
		// "searchFun":"WendaAsk.sendSearchQuestion"
		// //"enterFun":"enterAction"
		// });
		scrollEvent = "WendaAsk.searchQTitleObj.setConfig({width:395})";

		WendaAsk.searchQTitleObj = WendaAsk.QTitleObjCommon;

		// 文本框的事件,从新绑定
		setTimeout(function() {
			WendaAsk.askTxtEvent();
		}, 10);
	},
	/**
	 * 发送搜索问题请求
	 * 
	 * @param keyword
	 */
	sendSearchQuestion : function(keyword) {
		Wenda.post(Constans.BASE_PATH
				+ "json/qdetailJsonAction!searchQuestions.action", {
			"keyword" : keyword
		}, function(datas) {
			WendaAsk.searchTitleListCallBack(datas, keyword, "question");
		}, 'json');
	},
	/**
	 * 搜索回调
	 * 
	 * @param datas
	 * @param keyword
	 * @param type
	 */
	searchTitleListCallBack : function(datas, keyword, type) {
		var html = "";

		if (datas.questions != null && datas.questions.length > 0) {
			// if(cacheData["qcontent"]){
			html += '<div style="-moz-user-select: none;background: none repeat scroll 0 0 #D2E1E8 !important;color: ;">您想问的是不是下面的问题？'
					+ '<a href="#" title="关闭" name="close" id="closeSearchTitleList" style="-moz-user-select: none;">'
					+ '不是&nbsp;&nbsp;<img src="../img/close.gif"/>&nbsp;</a></div>';
			// <span class="x-m" style="-moz-user-select: none;"><img
			// src="../img/close.gif"/></span>
			// }
			for ( var i = 0; i < datas.questions.length; i++) {
				html += WendaAsk.parseQuestionsData(datas.questions[i]);
			}

			WendaAsk.searchQTitleObj.setHtml({
				"html" : html,
				"keyword" : keyword
			});
			$("#closeSearchTitleList").bind("click", function() {
				WendaAsk.searchQTitleObj.clean();
			});
		}

	},
	/**
	 * 拼装html
	 * 
	 * @param question
	 * @returns {String}
	 */
	parseQuestionsData : function(question) {
		var html = "";
		html = '<div style="-moz-user-select: none;">' + '<a href="' + basePath
				+ 'question/question!fetchQuestion.action?qid=' + question.qid
				+ '" id="rlq-' + question.qid + '" name="rlq" class="xu">'
				+ question.qtitle + '</a>'
				// +'<span class="xer" style="-moz-user-select:
				// none;">问题</span>'
				+ '</div>';
		return html;
	}

};

window.noUseLink = function() {
	if ($.browser.msie) {
		window
				.setTimeout(
						function() {
							$("a")
									.each(
											function() {
												var href = this.href;
												if (!href
														|| (0 > href
																.indexOf("wenda/")
																&& 0 > href
																		.indexOf("http://") && 0 > href
																.indexOf("https://"))) {
													// this.href = "###";
													$(this).bind("click",
															function(e) {
																return false;
															});
												}
											});
						}, 500);
	}
}